#include "logger.h"

#include <QCoreApplication>
#include <QDir>
#include <QException>
#include <QDateTime>
#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>

//QString g_configFile;
QFile* g_pFile = nullptr;

void customMessageHandler(QtMsgType type,
     const QMessageLogContext & context, const QString &msg)
{
   QString strType;
   switch (type) {
   case QtDebugMsg:
       strType = "Debug";
       break;
   case QtInfoMsg:
       strType = "Info";
       break;
   case QtWarningMsg:
       strType = "Warning";
       break;
   case QtCriticalMsg:
       strType = "Critical";
       break;
   case QtFatalMsg:
       strType = "Fatal";
       break;
   }

   QDateTime dt = QDateTime::currentDateTime();

   //TODO:check file size,and to rotate

   std::string temp (context.file);
   std::string::size_type pos = temp.find_last_of('\\');
   std::string fileName ("");
   if( std::string::npos != pos)
   {
       fileName = temp.substr(pos+1,temp.size()-pos-1);
   }
   if(!g_pFile->isOpen())
   {
       if(!g_pFile->open(QIODevice::WriteOnly |
                   QIODevice::Append))
       {
           return;
       }
   }

   //format
   QTextStream ts(g_pFile);
   ts << "[" << dt.toString("yyyy-MM-dd hh:mm:ss:zzz") << "]";
   ts << "[" << strType << "]";
   ts << "[" << fileName.c_str() <<
         "," << std::to_string(context.line).c_str() <<"]";
   ts << msg << "\r\n";

   g_pFile->close();
//   std::stringstream ss;
//   ss << "[" << dt.toString("yyyy-MM-dd hh:mm:ss:zzz").toStdString().c_str() << "]";
//   ss << "[" << strType.toStdString().c_str() << "]";
//   ss << "[" << fileName.c_str() <<
//         "," << std::to_string(context.line).c_str() <<"]";
//   ss << msg.toStdString().c_str() << "\r\n";
//   g_pFile->write(ss.str().c_str(),ss.str().size());
//   g_pFile->flush();
}

Logger::Logger(QString fileName)
{
    if(init_logger(fileName))
    {
        qDebug() << "Init Logger Successful";
    }
}

bool Logger::init_logger(QString fileName)
{
    try
    {
        QString dirPath = QCoreApplication::applicationDirPath();
        dirPath = dirPath + "../../logs";
        //check if exists
        QDir dir (dirPath);
        dirPath = dir.absolutePath();
        if(! dir.exists())
        {
            if(!dir.mkpath(dirPath))
            {
               dirPath = "./";
            }
        }
        QString filePathName = dirPath + "/" + fileName;
        g_pFile = new QFile(filePathName);
        if(!g_pFile->open(QIODevice::WriteOnly |
                    QIODevice::Append))
        {
            qWarning() << "Open log file error";
            return false;
        }
        qInstallMessageHandler(customMessageHandler);
        g_pFile->close();
    }
    catch(QException& ex)
    {
        qWarning() << ex.what();
        return false;
    }
    return true;
}
